import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'bp_alicloud_push_platform_interface.dart';

/// An implementation of [BpAlicloudPushPlatform] that uses method channels.
class MethodChannelBpAlicloudPush extends BpAlicloudPushPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('bp_alicloud_push');

  final eventChannel = const EventChannel('bp_alicloud_push_event');

  @override
  Future<String?> getPlatformVersion() async {
    final version =
        await methodChannel.invokeMethod<String>('getPlatformVersion');
    return version;
  }

  @override
  Future<bool?> bindAccount(String account) async {
    var arguments = {'account': account};
    return await methodChannel.invokeMethod<bool>('bindAccount', arguments);
  }

  @override
  Future<bool?> unbindAccount() async {
    return await methodChannel.invokeMethod<bool>('unbindAccount');
  }

  @override
  void listenerEvent(Function(dynamic data) onData) {
    eventChannel.receiveBroadcastStream().listen(onData);
  }

  @override
  void receiver(Function(dynamic data) onData) {
    methodChannel.setMethodCallHandler((call) => _handle(call, onData));
  }

  Future<dynamic> _handle(
      MethodCall call, Function(dynamic data) onData) async {
    if (call.method == 'receiver') onData(call.arguments);
  }
}
